Component({
  data: {
    selected: 0,
    color: "#999",
    selectedColor: "#2575fc",
    // 所有可用的标签项
    allTabs: [{
      pagePath: "/pages/index/index",
      text: "首页",
      iconClass: "icon-home",
      showForRoles: ["user", "admin"]
    }, {
      pagePath: "/pages/Transaction/transaction",
      text: "交易",
      iconClass: "icon-transaction",
      showForRoles: ["user", "admin"]
    }, {
      pagePath: "/pages/analysis/analysis",
      text: "数据",
      iconClass: "icon-analysis",
      showForRoles: ["admin"]
    }, {
      pagePath: "/pages/Message/message",
      text: "消息",
      iconClass: "icon-message",
      showForRoles: ["user", "admin"]
    }, {
      pagePath: "/pages/tenant/tenant",
      text: "租户",
      iconClass: "icon-tenant",
      showForRoles: ["admin"]
    }, {
      pagePath: "/pages/user/user",
      text: "我的",
      iconClass: "icon-user",
      showForRoles: ["user", "admin"]
    }],
    list: [] // 实际显示的标签列表，将根据用户角色动态生成
  },
  attached() {
    // 初始化时获取用户角色并过滤标签栏
    this.updateTabBarByRole()
    
    // 设置当前选中的标签
    this.setData({
      selected: this.getTabBarIndex()
    })
    
    // 监听用户角色变化
    const app = getApp()
    // 如果存在app.watchUserRole则清除
    if (app.watchUserRole) {
      app.watchUserRole = null
    }
    
    // 设置监听器
    app.watchUserRole = () => {
      this.updateTabBarByRole()
      this.setData({
        selected: this.getTabBarIndex()
      })
    }
  },
  detached() {
    // 组件销毁时清除监听器
    const app = getApp()
    if (app.watchUserRole) {
      app.watchUserRole = null
    }
  },
  pageLifetimes: {
    show: function() {
      // 页面显示时更新标签栏状态
      this.updateTabBarByRole()
      this.setData({
        selected: this.getTabBarIndex()
      })
    }
  },
  methods: {
    // 根据用户角色更新标签栏
    updateTabBarByRole() {
      const app = getApp()
      const userRole = app.globalData.userRole || 'user'
      
      // 根据用户角色过滤标签项
      const filteredTabs = this.data.allTabs.filter(tab => 
        tab.showForRoles.includes(userRole)
      )
      
      this.setData({
        list: filteredTabs
      })
    },
    
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({
        url
      })
      this.setData({
        selected: data.index
      })
    },
    
    getTabBarIndex() {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const url = `/${currentPage.route}`
      
      for (let i = 0; i < this.data.list.length; i++) {
        if (this.data.list[i].pagePath === url) {
          return i
        }
      }
      return 0
    },
    
    // 跳转到发布商品页面
    goToPublish() {
      wx.navigateTo({
        url: '/pages/Product/product'
      })
    }
  }
}) 